const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;

// 全局变量
const appid = "1104512706"

// 中间件
app.use(express.json());
app.use(express.static('public'));

// hash33加密函数
function hash33加密(t) {
    let e = 0;
    for (let i = 0; i < t.length; i++) {
        e += (e << 5) + t.charCodeAt(i);
    }
    return 2147483647 & e;
}

// 文本处理函数
function 文本_取出中间文本(原文, 左边文本, 右边文本) {
    const leftIndex = 原文.indexOf(左边文本);
    if (leftIndex === -1) return '';
    const start = leftIndex + 左边文本.length;
    const rightIndex = 原文.indexOf(右边文本, start);
    if (rightIndex === -1) return '';
    return 原文.substring(start, rightIndex);
}

// 获取二维码
app.get('/api/getQRCode', async (req, res) => {
    try {
        let qrsig = null
        let ptqrtoken = null

        // 生成动态时间戳（确保每次二维码都不一样）
        const timestamp = Date.now() / 1000; // 当前时间戳（秒）
        const randomSuffix = Math.random().toString().substring(2, 8); // 随机后缀
        const dynamicTimestamp = `0.${timestamp}${randomSuffix}`;

        const qrUrl = `https://xui.ptlogin2.qq.com/ssl/ptqrshow?s=8&e=0&appid=716027609&type=0&t=${dynamicTimestamp}&u1=http%3A%2F%2Fconnect.qq.com&daid=381&pt_3rd_aid=${appid}`;
        

        console.log('生成的二维码URL:', qrUrl);

        // 获取二维码图片
        const response = await axios.get(qrUrl, {
            responseType: 'arraybuffer',
            headers: {
                'User-Agent': 'Mozilla/5.0 (Linux; Android 12; DCO-AL00 Build/V417IR; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/91.0.4472.114 Mobile Safari/537.36 V1_AND_SQ_9.0.15_5626_YYB_D QQ/9.0.15.14970 NetType/WIFI WebP/0.4.1 AppId/537202228 Pixel/540 StatusBarHeight/37 SimpleUISwitch/0 QQTheme/1000 StudyMode/0 CurrentMode/0 CurrentFontScale/1.0 GlobalDensityScale/1.0 AllowLandscape/false InMagicWin/0',
                'Accept': 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
                'X-Requested-With': 'com.tencent.mobileqq',
                'Sec-Fetch-Site': 'same-origin',
                'Sec-Fetch-Mode': 'no-cors',
                'Sec-Fetch-Dest': 'image',
                'Referer': 'https://xui.ptlogin2.qq.com/cgi-bin/xlogin?pt_enable_pwd=1&appid=716027609&pt_3rd_aid=1106087470&daid=381&pt_skey_valid=0&style=35&force_qr=1&autorefresh=1&s_url=http%3A%2F%2Fconnect.qq.com&refer_cgi=m_authorize&ucheck=1&fall_to_wv=1&status_os=12&redirect_uri=auth%3A%2F%2Ftauth.qq.com%2F&client_id=1106087470&pf=openmobile_android&response_type=token&scope=all&sdkp=a&sdkv=3.5.2.lite&sign=FD17630D63DCE69539E06C154E87C2A8&status_machine=DCO-AL00&switch=1&time=1706443063&_wv=16777218&qr_login=1&loginfrom=main&h5sig=U7ej7mTpf-a9tLiUOK4SJdJ-HhT21ajsTJfS_nugbk8&loginty=6'
            }
        });

        // 从响应头获取qrsig
        const setCookie = response.headers['set-cookie'];
        if (setCookie) {
            const qrsigMatch = setCookie.toString().match(/qrsig=([^;]+)/);
            if (qrsigMatch && qrsigMatch[1]) {
                qrsig = qrsigMatch[1];
                console.log('获取到qrsig:', qrsig);
            }
        }

        if (!qrsig) {
            console.error('未能从响应头中获取qrsig');
            console.error('响应头:', response.headers);
            return res.json({ success: false, message: '获取qrsig失败' });
        }

        // 计算ptqrtoken
        ptqrtoken = hash33加密(qrsig);
        console.log('计算ptqrtoken:', ptqrtoken);

        // 使用腾讯返回的二维码图片（而不是重新生成）
        const qrDataUrl = `data:image/png;base64,${Buffer.from(response.data).toString('base64')}`;


        res.json({
            success: true,
            qrCode: qrDataUrl,
            qrsig: qrsig,
            ptqrtoken: ptqrtoken,
            timestamp: dynamicTimestamp
        });

    } catch (error) {
        console.error('获取二维码失败:', error);
        if (error.response) {
            console.error('响应状态:', error.response.status);
            console.error('响应头:', error.response.headers);
        }
        res.json({ success: false, message: '获取二维码失败' });
    }
});

// 查询授权状态
app.get('/api/checkLoginStatus', async (req, res) => {

    const { qrsig, ptqrtoken } = req.query;
    // console.log('checkLoginStatus---qrsig:', qrsig);
    // console.log('checkLoginStatus---ptqrtoken:', ptqrtoken);

    try {
        const url = `https://xui.ptlogin2.qq.com/ssl/ptqrlogin?u1=http%3A%2F%2Fconnect.qq.com&from_ui=1&type=1&ptlang=2052&ptqrtoken=${ptqrtoken}&daid=381&aid=716027609&pt_3rd_aid=${appid}&pt_openlogin_data=which%3D%26refer_cgi%3Dm_authorize%26response_type%3Dtoken%26client_id%3D${appid}%26state%3D%26display%3D%26openapi%3D1011%26switch%3D1%26src%3D1%26sdkv%3D3.5.2.lite%26sdkp%3Da%26tid%3D1706443065%26pf%3Dopenmobile_android%26need_pay%3D0%26browser%3D0%26browser_error%3D%26serial%3D%26token_key%3D%26redirect_uri%3Dauth%253A%252F%252Ftauth.qq.com%252F%26sign%3DFD17630D63DCE69539E06C154E87C2A8%26time%3D1706443063%26status_version%3D%26status_os%3D12%26status_machine%3DDCO-AL00%26page_type%3D1%26has_auth%3D1%26update_auth%3D1%26auth_time%3D1706443066436%26loginfrom%3Dmain%26h5sig%3DU7ej7mTpf-a9tLiUOK4SJdJ-HhT21ajsTJfS_nugbk8%26loginty%3D6%26&device=2&ptopt=1&pt_uistyle=35&jsver=v1.48.1&aegis_uid=dc0d7f000001e533-1a677cf05048c7d1-2475&r=0.778137550919271`;

        const response = await axios.get(url, {
            headers: {
                'Cookie': `qrsig=${qrsig}`,
            }
        });

        const red = response.data;

        if (red.includes('登录成功')) {
            const 网名 = 文本_取出中间文本(red, "登录成功！', '", "'");
            const op信息 = await 获取op信息(red, 网名);

            res.json({
                success: true,
                status: 'success',
                nickname: 网名,
                opInfo: op信息
            });

        } else if (red.includes('本次登录已被拒绝') || red.includes('二维码已失效')) {
            res.json({
                success: false,
                status: 'expired',
                message: '二维码已失效'
            });
        } else {
            console.log("认证信息--red", red);
            res.json({
                success: true,
                status: 'waiting',
                message: '等待扫码'
            });
        }
    } catch (error) {
        console.error('查询状态失败:', error.message);
        res.json({ success: false, message: '查询状态失败' });
    }
});

// 获取op信息
async function 获取op信息(red, 网名) {
    try {
        const openid = 文本_取出中间文本(red, 'openid=', '&');
        const access_token = 文本_取出中间文本(red, 'access_token=', '&');
        const pay_token = 文本_取出中间文本(red, 'pay_token=', '&');
        const key = 文本_取出中间文本(red, 'key=', '&');
        const auth_time = 文本_取出中间文本(red, 'auth_time=', '&');

        // 获取QQ号码
        const qq = await 获取QQ号码(openid, access_token);

        // 获取信用分
        const 信用分 = "无"//await 获取信用分(openid, access_token);

        //有些游戏限制信用分低的注册游戏，或者发言加好友
        //console.log("信用分", 信用分)

        let OP数据 = `${openid}|${access_token}|${pay_token}|${key}|${auth_time}`;
        //if (信用分) {
        //    OP数据 = `${openid}|${access_token}|${pay_token}|${key}|${auth_time}-${信用分}`;
        //} else {
        //    OP数据 = `${openid}|${access_token}|${pay_token}|${key}|${auth_time}`;
        //}

        return {
            qq,
            nickname: 网名,
            openid,
            access_token,
            pay_token,
            key,
            auth_time,
            creditScore: 信用分,
            opData: OP数据,


        };

    } catch (error) {
        console.error('获取op信息失败:', error);
        throw error;
    }
}

// 获取QQ号码
async function 获取QQ号码(openid, access_token) {
    try {
        const 协议头 = {
            "T-APPID": appid,
            "T-ACCOUNT-TYPE": "qc",
            "T-ACCESS-TOKEN": access_token,
            'T-OPENID': openid
        };

        const response = await axios.post('https://bgw.xinyue.qq.com/xyapi.PageService/GetUserInfo', {}, {
            headers: 协议头
        });


        // console.log('用户信息profile:', response.data.data.profile);

        if (response.data && response.data.data && response.data.data.profile) {
            return response.data.data.profile.user_id;
        }

        return '未知';

    } catch (error) {
        console.error('获取QQ号码失败:', error);
        return '获取失败';
    }
}

// 获取信用分--这里不能用,不影响登录
async function 获取信用分(openid, access_token) {
    try {
        const cookie = `acctype=qc;appid=1105483033;openid=${openid};access_token=${access_token}`;

        const response = await axios.get('https://gamecredit.qq.com/api/qq/proxy/query_common_credit', {
            headers: {
                'Cookie': cookie,
            },
            maxRedirects: 0
        });

        console.log('信用分:', response.data);
        if (response.data && response.data.data) {
            return response.data.data.score;
        }

        return null;

    } catch (error) {
        console.error('获取信用分失败:', error);
        return null;
    }
}

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
});